<template>
	<div class="countdown">
		剩余时间：{{ remainingTime }}
	</div>
</template>

<script setup lang="ts">
	import { ref, onMounted, onUnmounted, watch } from 'vue';
	import { useStore } from 'vuex'; 
	const store = useStore();
	let hasExpired = false;

	const calculateRemainingTime = (expireTime : string) : {
		text : string;
		isWithin30Minutes : boolean;
		isExpired : boolean;
	} => {
		if (!expireTime) return {
			text: "0分钟",
			isWithin30Minutes: false,
			isExpired: true
		};

		const now = new Date().getTime();
		const expire = new Date(expireTime).getTime();
		const diffMs = expire - now;

		if (diffMs <= 0) return {
			text: "0分钟",
			isWithin30Minutes: false,
			isExpired: true
		};

		const thirtyMinutesMs = 30 * 60 * 1000;
		const isWithin30Minutes = diffMs <= thirtyMinutesMs;

		if (isWithin30Minutes) {
			const totalSeconds = Math.floor(diffMs / 1000);
			const minutes = Math.floor(totalSeconds / 60);
			const seconds = totalSeconds % 60;
			return {
				text: `${minutes}分钟${seconds}秒`,
				isWithin30Minutes: true,
				isExpired: false
			};
		}

		const days = Math.floor(diffMs / 86400000);
		const hours = Math.floor((diffMs % 86400000) / 3600000);
		const minutes = Math.floor((diffMs % 3600000) / 60000);

		const timeParts : string[] = [];
		if (days > 0) timeParts.push(`${days}天`);
		if (hours > 0) timeParts.push(`${hours}小时`);
		if (minutes > 0) timeParts.push(`${minutes}分钟`);

		if (timeParts.length === 0) {
			return { text: "30分钟以上", isWithin30Minutes: false, isExpired: false };
		}

		return {
			text: timeParts.join(""),
			isWithin30Minutes: false,
			isExpired: false
		};
	};

	const props = defineProps<{
		expireTime : string;
		is_trial : number;
	}>();
	const remainingTime = ref("");
	let timer : number | null = null;

	const updateRemainingTime = () => {
		const result = calculateRemainingTime(props.expireTime);
		remainingTime.value = result.text;
		if (result.isExpired && !hasExpired) {
			hasExpired = true; 
			// 仅当is_trial为1时执行以下代码
			if (props.is_trial === 1) {
				const Userdata_obj = JSON.parse(JSON.stringify(store.state.Userdata));
				Userdata_obj.showTrialFinished = true;
				store.commit('localStorage_userdata', Userdata_obj);
			}
			// 定时器清除逻辑不受is_trial影响，始终执行
			if (timer) {
				clearInterval(timer);
				timer = null;
			}
		}

		if (result.isWithin30Minutes && !timer && !result.isExpired) {
			timer = window.setInterval(updateRemainingTime, 1000);
		} else if (!result.isWithin30Minutes && timer) {
			clearInterval(timer);
			timer = null;
		}
	};

	onMounted(() => {
		updateRemainingTime();
	});

	onUnmounted(() => {
		if (timer) {
			clearInterval(timer);
			timer = null;
		}
	});

	watch(() => props.expireTime, () => {
		hasExpired = false;
		if (timer) {
			clearInterval(timer);
			timer = null;
		}
		updateRemainingTime();
	});
</script>